package com.buss.customer.dao.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.buss.core.persistence.BaseDao;
import com.buss.core.persistence.ResultList;
import com.buss.core.utils.StringUtil;
import com.buss.customer.dao.CustomerAccountDao;
import com.buss.customer.model.CustomerAccount;

@Repository
public class CustomerAccountDaoImpl implements CustomerAccountDao {

	@Autowired
	private BaseDao<CustomerAccount> baseDao;
	
	@Override
	public CustomerAccount saveAccount(CustomerAccount account) {
		if(account.getIsDefault()){
			String sql = "update CustomerAccount account set account.isDefault = :isDefault where account.customerId = :customerId";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("isDefault", false);
			params.put("customerId", account.getCustomerId());
			baseDao.excuteHsql(sql, params);
		}
		return baseDao.saveOrEdit(account);
	}

	@Override
	public void editAccount(CustomerAccount account) {
		if(account.getIsDefault()){
			String sql = "update CustomerAccount account set account.isDefault = :isDefault where account.customerId = :customerId";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("isDefault", false);
			params.put("customerId", account.getCustomerId());
			baseDao.excuteHsql(sql, params);
		}
		baseDao.edit(account);
	}

	@Override
	public void removeAccount(Long[] ids) {
		String sql = "delete from CustomerAccount account where account.id in (:ids)";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("ids", ids);
		baseDao.excuteHsql(sql, params);
	}

	@Override
	public CustomerAccount loadAccount(Long id) {
		return baseDao.get(id, CustomerAccount.class);
	}

	@Override
	public ResultList<CustomerAccount> queryAccount(Long customerId,
			String accountName, String accountNumber) {
		String sql = "select account from CustomerAccount account where account.customerId = :customerId ";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("customerId", customerId);
		if(StringUtil.isNotEmpty(accountName)){
			sql += " and account.accountName like :accountName ";
			params.put("accountName", "%" + accountName + "%");
		}
		if(StringUtil.isNotEmpty(accountNumber)){
			sql += " and account.accountNumber = :accountNumber ";
			params.put("accountNumber", accountNumber);
		}
		return baseDao.queryHsql(sql, params, null);
	}

}
